package com.nativetalk.service.live.update;

import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.FoundChange.TdNtTeaFoundChangeInsert;
import com.nativetalk.bean.live.*;
import com.nativetalk.bean.teacher.TdNtTeacherIndex;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.oss.OssUtil;
import com.nativetalk.common.util.CommonUtil;
import com.nativetalk.common.util.DateUtil;
import com.nativetalk.common.util.JsonUtil;
import com.nativetalk.dao.*;
import com.nativetalk.service.live.search.LiveSearchServiceImpl;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lizhun on 16/5/14.
 * Modified by wangzheng on 17/02/28
 */
@Service
public class LiveUpdateServiceImpl implements LiveUpdateService {
    private static Logger logger = Logger.getLogger(LiveSearchServiceImpl.class);
    @Resource
    private TdNtLiveCourseDao tdNtLiveCourseDao;
    @Resource
    private TdNtLivePictureDao tdNtLivePictureDao;
    @Resource
    private TdNtLiveCourseHisDao tdNtLiveCourseHisDao;
    @Resource
    private TdNtTeaFoundChangeDao tdNtTeaFoundChangeDao;
    @Resource
    private TdNtTeacherDao tdNtTeacherDao;


    @Override
    public RetInfo deleteLivePicture(TdNtLivePictureDelete tdNtLivePictureDelete) {
        String logInfo = this.getClass().getName() + ":deleteLivePicture:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            tdNtLivePictureDelete.setIs_valid(1);
            tdNtLivePictureDao.updateTdNtLivePictureDelete(tdNtLivePictureDelete);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("删除图片成功");
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo updateLive(TdNtLiveCourseInsert tdNtLiveCourseInsert, CommonsMultipartFile cover) {
        String logInfo = this.getClass().getName() + ":addLiveCourse:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();

        try {
            if (!cover.isEmpty()) {
                /**
                 * 上传封面图片
                 */
                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setContentLength(cover.getSize());
                String cover_src = Constants.FILE + "/" + Constants.FILEIMG + "/image/teacher/live/" + tdNtLiveCourseInsert.getTea_id() + "/cover/"
                        + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System.currentTimeMillis())) + "2" + cover.getOriginalFilename().substring(cover.getOriginalFilename().lastIndexOf("."));
                OssUtil.uploadInputStream(cover.getInputStream(), objectMetadata, cover_src);
                tdNtLiveCourseInsert.setCover(cover_src);
            }
            /**
             * 更新直播课程
             */

            tdNtLiveCourseInsert.setLive_cou_state("1");
            tdNtLiveCourseDao.updateTdNtLiveCourse(tdNtLiveCourseInsert);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setObj("更新成功");
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo start(TdNtLiveCourseHisUpdate tdNtLiveCourseHisUpdate) {
        String logInfo = this.getClass().getName() + ":start:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();

        try {
            tdNtLiveCourseHisUpdate.setLive_cou_state("2");
            tdNtLiveCourseHisDao.updateTdNtLiveCourseHisStart(tdNtLiveCourseHisUpdate);
            /**
             * 查找所有已购买直播用户发推送通知
             */
            Map<String, Object> map = new HashMap<>();
//            map.put("conference_title",tdNtLiveCourseHisUpdate.getConference_title());
//            map.put("conference_url",tdNtLiveCourseHisUpdate.getConference_url());
//            map.put("conference_password",tdNtLiveCourseHisUpdate.getConference_password());
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("开始成功");
            retInfo.setObj(map);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    //结束直播
    @Override
    public RetInfo end(TdNtLiveCourseHisUpdate tdNtLiveCourseHisUpdate) {
        logger.info("\n结束直播-- params --->>" + JsonUtil.toJson(tdNtLiveCourseHisUpdate) + "\n");
        RetInfo retInfo = new RetInfo();
        try {
            // ==================== 1 更新直播记录 ====================
//            状态 1待直播2直播中3直播结束4已取消
            tdNtLiveCourseHisUpdate.setLive_cou_state("3");
            Date endTime = new Date();
            tdNtLiveCourseHisUpdate.setLive_end_time(new Timestamp(endTime.getTime()));
            // ==================== 2 更新直播老师资金变化记录 start =======================
            // 累计超过2/3的时间就给直播的钱，否则不给钱
            int live_cou_his_id = tdNtLiveCourseHisUpdate.getLive_cou_his_id();
            TdNtLiveCourseHisDetails tdNtLiveCourseHisDetails = tdNtLiveCourseHisDao.findTdNtLiveCourseHisDetails(live_cou_his_id);
            int live_cou_id = tdNtLiveCourseHisDetails.getLive_cou_id();
            TdNtLiveCourseDetail liveCourseDetail = tdNtLiveCourseDao.findTdNtLiveCourseDetail(live_cou_id);
            logger.info("直播课live_cou_id：" + live_cou_id);
            logger.info("直播课实例live_cou_his_id：" + live_cou_his_id);
            Date startTime = tdNtLiveCourseHisDetails.getLive_start_time();
            long currentDurationSecond = DateUtil.distanceSecond(startTime, endTime);//本次直播持续的秒数
            long currentDurationMinute = DateUtil.distanceMinute(startTime, endTime);//本次直播持续的分钟数

            logger.info("本次直时间：" + DateFormatUtils.format(startTime, "yyyy-MM-dd hh:mm:ss") + "<-->"
                    + DateFormatUtils.format(endTime, "yyyy-MM-dd hh:mm:ss") + " 持续时间：" + currentDurationSecond + "秒(" + currentDurationMinute + "分钟)");

            //查询该课上次直播已经结束的记录（排除课程未正常结束的）
            TdNtLiveCourseHisDetails lastCourseHisDetails = tdNtLiveCourseHisDao.findLastCourseHisDetails(live_cou_id);


            //设置课堂号和视频编号
            int instance_num = -1;
            int instance_video_num = -1;
            int is_charged = 0;

            if (lastCourseHisDetails != null) {
                instance_num = lastCourseHisDetails.getLive_cou_instance_num().intValue();//课堂号
                instance_video_num = lastCourseHisDetails.getLive_cou_instance_video_num().intValue();//视频编号
                is_charged = lastCourseHisDetails.getLive_is_charged().intValue();
                is_charged = is_charged == -1 ? Constants.Teacher.LiveChargedState.uncharged : is_charged;
                logger.info("上次直播已经结束的记录：live_cou_his_id:" + lastCourseHisDetails.getLive_cou_his_id() + "--- 课堂号：" + instance_num + ",视频编号:" + instance_video_num + "，是否计费：" + is_charged);
            } else {
                logger.info("上次直播已经结束的记录 null");
            }

            if (is_charged == Constants.Teacher.LiveChargedState.charged) {//上次直播未计费
                logger.info("上次直播已计费");
                int current_instance_num = (instance_num == -1 ? 0 : instance_num) + 1;//上次直播已计费，课堂号+1
                int current_instance_video_num = 1;//上次直播已计费，视频编号从1开始
                tdNtLiveCourseHisUpdate.setLive_cou_instance_num(current_instance_num);
                tdNtLiveCourseHisUpdate.setLive_cou_instance_video_num(current_instance_video_num);
                logger.info("本次直播记录--- 课堂号：" + current_instance_num + ",视频编号:" + current_instance_video_num);
            } else {//上次直播已计费
                logger.info("上次直播未计费");
                int current_instance_num = instance_num == -1 ? 1 : instance_num;
                int current_instance_video_num = (instance_video_num == -1 ? 0 : instance_video_num) + 1;
                tdNtLiveCourseHisUpdate.setLive_cou_instance_num(current_instance_num);//上次直播未计费，课堂号不变，属于同一堂课
                tdNtLiveCourseHisUpdate.setLive_cou_instance_video_num(current_instance_video_num);//上次直播未计费，属于同一堂课的视频，视频号+1
                logger.info("本次直播记录--- 课堂号：" + current_instance_num + ",视频编号:" + current_instance_video_num);
            }

            int planDuration = liveCourseDetail.getLive_cou_time();//直播课计划持续时间（单位：分钟）
            logger.info("直播课计划时长：" + planDuration + "分钟");
            Integer sumDuration2 = tdNtLiveCourseHisDao.findLiveSumDuration(live_cou_id);//查询未计费累计直播时间（单位：秒）
            int sumDuration = sumDuration2 == null ? 0 : sumDuration2;
            logger.info("除本次直播的未计费时间：" + sumDuration + "秒");
            logger.info("次直播的时间：" + currentDurationSecond + "秒");

            int factDuration = (int) (sumDuration + currentDurationSecond) / 60;//分钟

            int limit = (planDuration * 2) / 3;
            logger.info("总计应计费时间:（" + (sumDuration + currentDurationSecond) + "秒）" + factDuration + "分钟,计费阈值:" + limit + "分钟,是否计费：" + (factDuration > limit));
            if (factDuration > limit) {//累计时间超过2/3计费，添加一条费用记录
                logger.info("---------- 计费 start ----------");
                tdNtLiveCourseHisUpdate.setLive_is_charged(Constants.Teacher.LiveChargedState.charged);

                //    查询老师账户余额（)
                BigDecimal balance = tdNtTeacherDao.findTdNtTeacherBalance(tdNtLiveCourseHisUpdate.getTea_id());
                TdNtTeaFoundChangeInsert teaFoundChange = new TdNtTeaFoundChangeInsert();
                teaFoundChange.setTea_id(tdNtLiveCourseHisUpdate.getTea_id());
                teaFoundChange.setState(Constants.PayState.success);
                teaFoundChange.setTfchg_account(new BigDecimal(0.00d));
                teaFoundChange.setTfchg_front_amount(balance);
                //    查询该堂直播课的老师应得费用
                BigDecimal earned = liveCourseDetail.getLive_cou_amount();//赚得金额
                logger.info("老师赚取：" + earned.doubleValue());

                teaFoundChange.setTfchg_back_amount(balance.add(earned));//设置变化后的金额
                teaFoundChange.setTfchg_change_amount(earned);
                Date now = new Date();
                Timestamp now2 = new Timestamp(now.getTime());
                teaFoundChange.setTfchg_change_month(CommonUtil.getMonth(now));
                teaFoundChange.setTfchg_change_time(now2);
                teaFoundChange.setTfchg_change_type(Constants.fundFlowType.in);//
                teaFoundChange.setTfchg_counter_fee(new BigDecimal(0.00d));//暂时不设置，看看有什么影响，感觉没用处。
                teaFoundChange.setTfchg_number(CommonUtil.getOrderNub());
                teaFoundChange.setType(Constants.fundChangeTypeForTeacher.live_code);
                teaFoundChange.setTfchg_change_name(Constants.fundChangeTypeForTeacher.live_msg);
                tdNtTeaFoundChangeDao.insertTdNtTeaFoundChangeInsert(teaFoundChange);
                logger.info(" ---------- 资金变化记录 ok -----------Tfchg_id:" + teaFoundChange.getTfchg_id());

                // 更新老师余额
                TdNtTeacherIndex tdNtTeacherIndex = tdNtTeacherDao.findTdNtTeacherIndex(tdNtLiveCourseHisUpdate.getTea_id());
                tdNtTeacherIndex.setTea_balance(teaFoundChange.getTfchg_back_amount());
                tdNtTeacherIndex.setTea_total_balance(tdNtTeacherIndex.getTea_total_balance().add(earned));
                tdNtTeacherDao.updateTeacherBalance(tdNtTeacherIndex);
                logger.info(" ---------- 余额变动 ok tea_id:" + tdNtTeacherIndex.getTea_id() + "[" + balance.doubleValue() + "---->> " + teaFoundChange.getTfchg_back_amount().doubleValue() + "]-------------");

                logger.info(" ---------- 计费完成 -----------");

            } else {//不计费
                tdNtLiveCourseHisUpdate.setLive_is_charged(Constants.Teacher.LiveChargedState.uncharged);
                logger.info(" ---------- 不计费 -----------");
            }

            tdNtLiveCourseHisDao.updateTdNtLiveCourseHisEnd(tdNtLiveCourseHisUpdate);//更新直播状态和结束时间
            // ==================== 2 更新直播老师资金变化记录 end =======================


            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("");
            retInfo.setObj("结束成功");
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("====== end ======");
        return retInfo;
    }
}
